const express = require('express');
const router = express.Router();
// 模拟支付成功API
router.post('/simulate-payment', async (req, res) => {
  try {
    const { orderId, paymentMethod } = req.body;
    if (!orderId || !paymentMethod) {
      return res.status(400).json({ success: false, message: '缺少订单ID或支付方式' });
    }

    // 模拟支付处理延迟
    await new Promise(resolve => setTimeout(resolve, 1500));

    // 更新订单状态
    const updatedOrder = await orderModel.findOneAndUpdate(
      { orderNo: orderId },
      {
        paymentMethod: paymentMethod,
        paymentStatus: 'paid',
        status: 'paid',
        statusText: '已支付',
        statusTip: '支付成功'
      },
      { new: true }
    );

    if (!updatedOrder) {
      return res.status(404).json({ success: false, message: '订单不存在' });
    }

    res.json({ success: true, message: '支付成功', order: updatedOrder });
  } catch (error) {
    console.error('支付模拟失败:', error);
    res.status(500).json({ success: false, message: '支付处理失败' });
  }
});
const AlipaySdk = require('alipay-sdk');
const { orderModel } = require("../model/db");
const config = require('../config');
const fs = require('fs');
const path = require('path');

// 读取密钥文件内容
// 读取密钥文件内容
const privateKeyPath = 'private-key.pem';
const alipayPublicKeyPath = 'alipay-public-key.pem';

let privateKey, alipayPublicKey;
try {
  privateKey = fs.readFileSync(privateKeyPath, 'utf8');
  alipayPublicKey = fs.readFileSync(alipayPublicKeyPath, 'utf8');
} catch (error) {
  console.error('Error reading key files:', error);
  throw new Error('Failed to read key files: ' + error.message);
}

if (!privateKey) throw new Error('Private key is empty after reading file');
if (!alipayPublicKey) throw new Error('Alipay public key is empty after reading file');

// 1. 初始化支付宝SDK
const alipaySdk = new AlipaySdk({
  appId: config.alipay.appId,
  privateKey: fs.readFileSync(path.join(__dirname, '../private-key.pem'), 'ascii'), // Read from file
  alipayPublicKey: fs.readFileSync(path.join(__dirname, '../alipay-public-key.pem'), 'ascii'), // Read from file
  gateway: config.alipay.gateway,
});

// 2. 创建支付跳转URL的API
router.post('/alipay/checkout', async (req, res) => {
  let { orderId, amount } = req.body;

  try {
    if (!amount) {
      // 自动查找订单金额
      const order = await orderModel.findOne({ orderNo: orderId });
      if (!order) return res.status(404).send({ code: 404, msg: '订单不存在' });
      amount = order.pay;
    }
    const url = await alipaySdk.pageExec('alipay.trade.page.pay', {
      bizContent: {
        out_trade_no: orderId,
        total_amount: amount.toFixed(2),
        subject: `在线药店订单 - ${orderId}`,
        product_code: 'FAST_INSTANT_TRADE_PAY',
      },
      notifyUrl: 'http://localhost:3000/api/pay/alipay/notify',
      returnUrl: `http://localhost:5173/orders?orderId=${orderId}`,
    }, { method: 'GET' });
    res.send({ code: 200, paymentUrl: url });
  } catch (error) {
    console.error('Alipay checkout error:', error);
    res.status(500).send({ code: 500, msg: '创建支付订单失败' });
  }
});

// 3. 支付成功异步通知回调
router.post('/alipay/notify', async (req, res) => {
  try {
    const isSuccess = alipaySdk.checkSign(req.body);
    if (isSuccess && req.body.trade_status === 'TRADE_SUCCESS') {
      const orderId = req.body.out_trade_no;
      await orderModel.findOneAndUpdate(
        { id: orderId },
        { status: 'delivering', statusText: '待收货' }
      );
      res.send('success');
    } else {
      res.send('fail');
    }
  } catch (error) {
    console.error('Alipay notify error:', error);
    res.send('fail');
  }
});

module.exports = router;